import {ConfigDataEntity} from "../../../generate/entitas";
import {util} from "protobufjs";
import path = require("path");
import * as fs from "fs";
let ejs = require('ejs')

export default class BaseGenerator{
	checkStr : string
	columnEntity : ConfigDataEntity
	rootEntity : ConfigDataEntity
	checkData : any
	templatePath : string
	dirPath : string
	constructor(checkStr, checkData, columnEntity) {
		this.checkStr =	checkStr
		this.checkData = checkData
		this.columnEntity = columnEntity
		this.rootEntity = this.columnEntity.rootEntity.value
	}

	init()
	{
		this.beforeInit()
		this.templatePath = path.join(this.dirPath, "template")
		this.onInit()
	}

	beforeInit(){

	}

	onInit(){

	}


	//region  生成数据
	beforeGenData(entity : ConfigDataEntity){
		this.onBeforeGenData(entity)
	}

	afterGenData(entity : ConfigDataEntity){
		this.onAfterGenData(entity)
	}

	startGeData(entity : ConfigDataEntity){
		this.onStartGenData(entity)
	}

	//region   虚函数

	onStartGenData(entity : ConfigDataEntity){

	}

	onBeforeGenData(entity : ConfigDataEntity){

	}


	onAfterGenData(entity : ConfigDataEntity){

	}
	//endregion

	genData(entity : ConfigDataEntity){
	}
	//endregion


	//region  生成代码

	beforeGenCode(entity : ConfigDataEntity){
		this.onBeforeGenCode(entity)
	}

	afterGenCode(entity : ConfigDataEntity){
		this.onAfterGenCode(entity)
	}

	startGeCode(entity : ConfigDataEntity){
		this.onStartGeCode(entity)
	}



	genCode(entity : ConfigDataEntity){
	}
	//region   虚函数
	onStartGeCode(entity : ConfigDataEntity){

	}

	onBeforeGenCode(entity : ConfigDataEntity){

	}


	onAfterGenCode(entity : ConfigDataEntity){

	}
	//endregion
	//endregion


	generateWithFile(fileName, data = undefined){
		let file = fs.readFileSync(path.join(this.templatePath, fileName + ".ejs"), 'utf-8')
		let inData = {
			"headList" : this.rootEntity.memberHeadDataList.value,
			"className" : this.rootEntity.sheetName.value + "Config",
			"columnEntityList" : this.rootEntity.columnEntityList.value,
			"keyName" : this.rootEntity.memberHeadDataList.value[0].name,
			"keyType" : this.rootEntity.memberHeadDataList.value[0].normalType,
		}
		if (data != undefined){
			inData = Object.assign(inData, data)
		}
		let ret : string = ejs.render(file,inData)
		ret = ret.replace(/&lt;/g, "<").replace(/&gt;/g, ">")
			     .replace(/&amp;lt/g,"<").replace(/&amp;gt/g,">")
		         .replace(/&amp;lt;/g,"<").replace(/&amp;gt;/g,">")
				 .replace(/&#34;/g,'"')

		return ret;
	}
}